package com.hcy.app.screen.nfc

import android.R
import android.annotation.SuppressLint
import android.app.Activity
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.hcy.app.LocalNavController

@Composable
fun NFC_Page() {
    val navController = LocalNavController.current
    val lifecycleOwner = LocalLifecycleOwner.current
    var isActive by remember { mutableStateOf(false) }

    val context = LocalContext.current
    val activity = remember { (context as? Activity) } // 仅在初始组合时获取

    val nfcHandler = remember { NfcHandler() }
    val nfcResult by nfcHandler.nfcResult.collectAsState()
    lateinit var nfcAdapter: NfcAdapter


    DisposableEffect(lifecycleOwner) {
        nfcAdapter = NfcAdapter.getDefaultAdapter(activity) // 初始化 nfcAdapter

        val observer = object : DefaultLifecycleObserver {

            override fun onResume(owner: LifecycleOwner) {
                isActive = true
                nfcAdapter.enableReaderMode(
                    activity,
                    nfcHandler,
                    NfcAdapter.FLAG_READER_NFC_A,
                    null
                )
            }

            override fun onPause(owner: LifecycleOwner) {
                isActive = false
                nfcAdapter.disableReaderMode(activity)
            }
        }
        // 注册观察者
        lifecycleOwner.lifecycle.addObserver(observer)

        // 在 Composable 退出时移除观察者
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
    Column(
        modifier = Modifier.fillMaxWidth().systemBarsPadding().background(color = Color.Red)
    ) {
        // 工具栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
            ,
            horizontalArrangement = Arrangement.End,
        ) {
            IconButton(
                content ={
                    Icon(
                        imageVector = Icons.Default.Home,
                        contentDescription = "首页",
                        tint = Color.White
                    )
                },
                onClick = {
                    navController.navigate("home")
                }
            )
        }
        // nfc 读写区域
        NFC_Writer(nfcHandler=nfcHandler,isActive=isActive,nfcResult=nfcResult)
    }
}

@Preview
@Composable
fun NFC_WriterPre(){
    NFC_Writer()
}

@Composable
fun NFC_Writer(nfcHandler:NfcHandler=NfcHandler(),isActive: Boolean=false,nfcResult: String=""){
    val context = LocalContext.current
    var msgStr by remember { mutableStateOf("") }
    var wifiStr by remember { mutableStateOf("") }
    var copyStr by remember { mutableStateOf("") }

    Column(modifier = Modifier
        .fillMaxWidth()
        ,
        horizontalAlignment = Alignment.CenterHorizontally // 所有子项水平居中
    ) {

        Text(
            text="设备NFC读写支持状态：$isActive",
            modifier = Modifier
                .align(Alignment.Start) // 强制左对齐,覆盖掉父元素的居中样式
                .padding(start = 16.dp) // 添加左边距
            )
        Text(
            text = "标签信息：$nfcResult",
            modifier = Modifier
                .align(Alignment.Start) // 强制左对齐
                .padding(start = 16.dp) // 添加左边距
            )
        TextField( value = msgStr, onValueChange ={ newText -> msgStr = newText },
            modifier = Modifier
                .fillMaxWidth()
//                .height(40.dp
                )
        Button(onClick = {
            if (msgStr.isNotEmpty()){
                val b= NFCUtils.writeDataToNfcTag(nfcHandler.currentTag.value,msgStr)
                if (b){
                    Toast.makeText(context, "写入成功", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText(context, "写入失败", Toast.LENGTH_SHORT).show()
                }
            }

        }) {
            Text("写入文本信息")
        }

        TextField( value = wifiStr, onValueChange ={ newText -> wifiStr = newText },
            modifier = Modifier
                .fillMaxWidth()
//                .height(40.dp)
        )
        Button(onClick = {}) {
            Text("写入wifi信息")
        }
        TextField( value = copyStr, onValueChange ={ newText -> copyStr = newText },
            modifier = Modifier
                .fillMaxWidth()
                .height(40.dp))
        Row {
            Button(onClick = {}) {
                Text("nfc复制")
            }
            Button(onClick = {}) {
                Text("nfc拷贝")
            }
        }

    }

}
